package com.lzx.adx.report.util;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;

public class H5UrlReplacer {

    public static String replaceH5Url(String originalUrl, String newH5Url) throws URISyntaxException, UnsupportedEncodingException {
        // 解析原始URL
        URI uri = new URI(originalUrl);

        // 分割查询参数
        String query = uri.getQuery();
        if (query == null) {
            query = "";
        }

        // 解析查询参数到Map中
        Map<String, String> queryParams = splitQuery(query);

        // 替换h5Url参数值
        queryParams.put("h5Url", URLEncoder.encode(newH5Url, StandardCharsets.UTF_8.toString()));

        // 重新构建查询字符串
        String newQuery = buildQueryString(queryParams);

        // 构建新的URI
        URI newUri = new URI(
                uri.getScheme(),
                uri.getAuthority(),
                uri.getPath(),
                newQuery,
                uri.getFragment()
        );

        return newUri.toString();
    }

    private static Map<String, String> splitQuery(String query) {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        if (query == null || query.isEmpty()) {
            return queryPairs;
        }

        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            if (idx > 0) {
                String key = pair.substring(0, idx);
                String value = pair.substring(idx + 1);
                queryPairs.put(key, value);
            } else {
                queryPairs.put(pair, "");
            }
        }
        return queryPairs;
    }

    private static String buildQueryString(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;

        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!first) {
                sb.append("&");
            }
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue());
            first = false;
        }
        return sb.toString();
    }

    public static String getH5Url(String originalUrl) {

        try {
            // 解析原始URL
            URI uri = new URI(originalUrl);

            // 分割查询参数
            String query = uri.getQuery();
            if (query == null) {
                query = "";
            }

            // 解析查询参数到Map中
            Map<String, String> queryParams = splitQuery(query);

            return queryParams.get("h5Url");
        }catch (Exception e){

        }
      return null;
    }
}
